package com.hexu.event.view;

import com.hexu.event.controller.LoginInController;
import com.hexu.event.entity.Administrator;
import com.hexu.event.entity.Attractions;
import com.hexu.event.entity.User;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import com.hexu.event.util.StageUtil;

import java.util.ArrayList;
import java.util.List;

import static com.hexu.event.util.ServiceUtil.*;
import static com.hexu.event.view.VerificationCode.refreshVerificationCode;
import static com.hexu.event.view.VerificationCode.verificationCode;

public class LoginInView extends Application {

    public static void main(String[] args) {
        launch(args);//启动
    }

    //设置标签
    Label labelPhoneNumber = new Label("账号");
    Label labelPassword = new Label("密码");
    Label labelTourismSystem = new Label("XX旅游系统登录");

    //输入验证码
    static TextField textFieldVerificationCode = new TextField();

    //创建一个空的TextField对象
    static TextField phoneNumber = new TextField();
    //创建密码字段
    static PasswordField password = new PasswordField();

    //设置按钮
    Button login = new Button("登录");
    Button register = new Button("注册");
    Button visitorsLogin = new Button("游客登录");

    //生成验证码
    static ImageView imageView = new ImageView();

    //设置复选框
    static CheckBox rememberPassword = new CheckBox("记住密码");
    //设置复选框选择的账号
    private static String selectPhoneNumber = null;

    @Override
    public void start(Stage primaryStage)throws Exception{
        //设置字体大小
        labelPhoneNumber.setFont(Font.font(14));
        labelPassword .setFont(Font.font(14));
        labelTourismSystem.setFont(Font.font(20));

        Tooltip tooltip = new Tooltip();
        phoneNumber.setTooltip(tooltip);
        phoneNumber.setPromptText("请输入11位手机号码");
        phoneNumber.setFocusTraversable(false);

        textFieldVerificationCode.clear();
        textFieldVerificationCode.setPromptText("输入验证码");
        textFieldVerificationCode.setMaxWidth(95);
        textFieldVerificationCode.setLayoutX(270);
        textFieldVerificationCode.setLayoutY(260);

        //创建网格布局
        GridPane gridPane = new GridPane();
        //设置颜色
        gridPane.setStyle("-fx-background-color: #FFF5EE");

        //设置网格位置
        gridPane.add(labelTourismSystem,1,0);
        gridPane.add(labelPhoneNumber,0,1);
        gridPane.add(phoneNumber,1,1);
        gridPane.add(labelPassword ,0,2);
        gridPane.add(password,1,2);
        gridPane.add(login,1,5);
        gridPane.add(rememberPassword,1,5);
        gridPane.add(register,0,5);
        gridPane.add(visitorsLogin,0,6);

        //设置水平间距
        gridPane.setHgap(5);
        //设置垂直间距
        gridPane.setVgap(15);

        //设置单独组件的上下左右的间距
        GridPane.setMargin(login,new Insets(0,0,0,120));
        //进行对齐
        gridPane.setAlignment(Pos.CENTER);

        rememberPassword.setSelected(false);

        // 把清单对象转换为JavaFX控件能够识别的数据对象
        ObservableList<String> obList = FXCollections.observableArrayList(getSnackList());
        // 依据指定数据创建下拉框
        ComboBox<String> comboBox = new ComboBox<String>(obList);

        //生成验证码
        refreshVerificationCode(imageView);
        imageView.setX(137);
        imageView.setY(252);

        Group group = new Group();
        group.getChildren().addAll(gridPane,comboBox,imageView,textFieldVerificationCode);
        gridPane.setMinHeight(500);
        gridPane.setMinWidth(500);
        comboBox.setLayoutX(380);
        comboBox.setLayoutY(183);
        comboBox.setMaxWidth(10);

        StageUtil.showStage(primaryStage,new Scene(group),500,500,"登录",false);

        //设置单击事件 新用户注册
        register.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                //关闭这个界面，打开注册界面
                primaryStage.close();
                try {
                    registerView.registerView(primaryStage);
                }catch (Exception ex){
                    ex.printStackTrace();
                }

            }
        });

        //超过11位手机号码就不能输入
        phoneNumber.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                if(newValue.length() > 11){
                    phoneNumber.setText(oldValue);
                }
            }
        });

        //设置游客登录单击事件
        visitorsLogin.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                //关闭这个界面，打开游客界面
                primaryStage.close();
                try {
                    visitorsView.visitorsView(primaryStage);
                }catch (Exception ex){
                    ex.printStackTrace();
                }

            }
        });

        //设置登录按钮单击事件
        login.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                loginSetOneAction(primaryStage);
            }
        });

        //设置 下拉框监听器
        comboBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                selectPhoneNumber = comboBox.getSelectionModel().getSelectedItem();
                phoneNumber.setText(selectPhoneNumber);
                rememberPassword.setSelected(false);
                //先消去之前的密码
                password.clear();
                //如果该账号是记住密码的
                if(loginInService.ifRemember(selectPhoneNumber)){
                    password.setText(loginInService.findPassword(selectPhoneNumber));
                    rememberPassword.setSelected(true);
                }

            }
        });

    }



    public static void loginSetOneAction(Stage  primaryStage){
        //获取数据库中的手机号及对应密码
        LoginInController loginInController = new LoginInController();

        //如果手机号和密码匹配并且验证码输入正确
        if(loginInController.login(phoneNumber.getText(),password.getText()) && verificationCode()){
            //取出景点的所有信息
            List<Attractions> listAttractionsAllInformation = attractionsService.getAttractionsInformation();
            //取出景点数量
            int attractionsCount = attractionsService.attractionsNumber();
            //关闭primaryStage
            primaryStage.close();

            //判断是谁登录
            int flag = loginInController.flagChoose();
            //用户登录
            if (flag == 1) {
                try {

                    //如果复选框被勾选了
                    if(rememberPassword.isSelected()){
                        loginInService.remember2(phoneNumber.getText());
                    }else{
                        loginInService.notRemember2(phoneNumber.getText());
                    }

                    userView.getUserInformation(phoneNumber.getText());
                    userView.userView(primaryStage);

                    phoneNumber.clear();
                    password.clear();
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }

            //管理员登录
            if(flag == 2){
                try {
                    //如果复选框被勾选了
                    if(rememberPassword.isSelected()){
                        loginInService.remember(phoneNumber.getText());
                    }else{
                        loginInService.notRemember(phoneNumber.getText());
                    }
                    administratorView.view(primaryStage,2,phoneNumber.getText(),attractionsCount,listAttractionsAllInformation);
                    phoneNumber.clear();
                    password.clear();
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }

        }else if(!verificationCode()){
            //验证码输入错误
            //生成验证码
            refreshVerificationCode(imageView);
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("消息");
            alert.setHeaderText("验证码错误！");
            alert.showAndWait();

        } else{

            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("消息");
            alert.setHeaderText("账号或密码错误！");
            alert.showAndWait();
            //JOptionPane.showMessageDialog(null, "登录失败");

        }

    }

    //判断验证码是否输入正确
    public static boolean verificationCode(){

        //如果输入的验证码和显示的相同
        if(textFieldVerificationCode.getText() != null && textFieldVerificationCode.getText().equals(verificationCode.toString())){
            return true;
        }else {
            return false;
        }

    }


    //初始化下拉框的信息
    public static List<String> getSnackList(){
        //传入用户信息
        List<User> userList = userService.getUserInformation();
        //传入用户数量
        int userNumber = userService.userNumber();
        List<String> snackList3 = new ArrayList<>();
        for(int i = 0;i < userNumber;i++){
            snackList3.add(userList.get(i).getPhoneNumber());
        }

        //传入管理员信息
        List<Administrator> administratorList = administratorService.getAdministratorPhoneNumber();
        //传入管理员数
        int administratorNumber = administratorService.administratorNumber();
        for(int i = 0;i < administratorNumber;i++){
            snackList3.add(administratorList.get(i).getPhoneNumber());
        }


        return snackList3;
    }

}
